package com.cskaoyan.controller.wx;


import com.cskaoyan.bean.*;
import com.cskaoyan.bean.wx.WxLoginRespVo;
import com.cskaoyan.bean.wx.WxUserBean;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.shiro.MallToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("wx/auth/")
public class WxAuthController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("login")
    public BaseRespVo login(@RequestBody User user){
        //先获得subject对象，直接通过SecurityUtils
        Subject subject = SecurityUtils.getSubject();
        MallToken wxToken = new MallToken(user.getUsername(),user.getPassword(), "wx");
        try {
            subject.login(wxToken);
        } catch (AuthenticationException e) {
            return BaseRespVo.fail("认证失败，请重新登录");
        }

        UserExample userExample = new UserExample();
        userExample.createCriteria().andPasswordEqualTo(user.getPassword()).andUsernameEqualTo(user.getUsername());
        List<User> users = userMapper.selectByExample(userExample);
        WxUserBean wxUserBean = new WxUserBean();
        wxUserBean.setAvatarUrl(users.get(0).getAvatar());
        wxUserBean.setNickName(user.getUsername());

        WxLoginRespVo wxLoginRespVo = new WxLoginRespVo();
        wxLoginRespVo.setUserInfo(wxUserBean);
        //维护同一个session 在业务逻辑代码中的实现就是 login方法返回ResponVo中的Data为SessionId
        String id =(String) subject.getSession().getId();
        wxLoginRespVo.setToken(id);
        wxLoginRespVo.setTokenExpire(new Date().toString());

        System.out.println("wx subject:是否验证"+subject.isAuthenticated()+" sessionid="+subject.getSession().getId());

        return BaseRespVo.ok(wxLoginRespVo);
    }

    @RequestMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

}
